# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(optparse)
library(gbm)
library(caret)
library(tidyverse)
library(readxl)
library(writexl)
library(e1071)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "../../data.xlsx", type = "character", help = "metabolite data file"),
  make_option("--g", default = "../../group.xlsx", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--config", default = "../../calculate_config.txt", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)
args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

sampleInfo <- read_xlsx(opt$g) %>%
  rename(ClassNote = Group) %>%
  select(c("SampleID", "ClassNote"))

head(sampleInfo)

parent <- paste0("./")
createWhenNoExist(parent)

originalData <- read_xlsx(opt$i) %>%
  rename(Metabolite = SampleID) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value")

configData <- read_tsv(opt$config, col_names = F) %>%
  set_colnames(c("arg", "value"))

kernel <- configGet(configData, "kernel")
cost <- configGet(configData, "cost") %>%
  as.numeric()
tolerance <- configGet(configData, "tolerance") %>%
  as.numeric()
epsilon <- configGet(configData, "epsilon") %>%
  as.numeric()
gamma <- configGet(configData, "gamma") %>%
  as.numeric()
coef0 <- configGet(configData, "coef0") %>%
  as.numeric()
degree <- configGet(configData, "degree") %>%
  as.numeric()

originalColumnNames <- colnames(originalData)

data <- originalData %>%
  inner_join(sampleInfo, by = c("SampleID")) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote)))
allTrainData <- data %>%
  column_to_rownames("SampleID")

numColumns <- c("年龄", "BMI", "腰围", "阿司匹林服药频率为每周几次", "您从多少岁开始养成每天都吸烟的习惯？",
                "扣除戒烟年数，您一共吸烟多少年？", "您平均每天吸烟多少支？",
                "在有烟雾的室内环境中，您与吸烟者共同居住或工作了多少年", "扣除戒烟年数，该吸烟者一共吸烟多少年",
                "该吸烟者平均每天吸烟多少支", "您每周有几天饮酒？", "白酒每周饮酒量", "您每周参加体育锻炼累计多长时间？")

load("../../folds.RData")
predictLists <- (1:k) %>%
  map(function(k) {
    testData <- allTrainData[flds[[k]],]
    trainData <- allTrainData[-flds[[k]],]
    x <- trainData %>%
      select(-c("ClassNote")) %>%
      mutate_at(vars(numColumns), as.numeric) %>%
      mutate_at(vars(-numColumns), factor) %>%
      mutate_all(as.numeric)

    testDataNoClass <- testData %>%
      select(-c("ClassNote")) %>%
      mutate_at(vars(numColumns), as.numeric) %>%
      mutate_at(vars(-numColumns), factor) %>%
      mutate_all(as.numeric) %>%
      as.data.frame()

    filterColumns <- x %>%
      sapply(nlevels) %>%
      keep(function(x) { x == 1 }) %>%
      names()
    print(filterColumns)

    x <- x %>%
      select(-filterColumns)

    testDataNoClass <- testDataNoClass %>%
      select(-filterColumns)

    common <- intersect(names(x), names(testDataNoClass))
    for (p in common) {
      if (class(x[[p]]) == "factor") {
        levels(testDataNoClass[[p]]) <- levels(x[[p]])
      }
    }

    y <- trainData$ClassNote

    finalGamma <- if (is.na(gamma)) {
      if (is.vector(x)) 1 else 1 / ncol(x)
    }else {
      gamma
    }

    svmRs <- svm(x, y, type = 'C', kernel = kernel, cost = cost, tolerance = tolerance, epsilon = epsilon,
                 gamma = finalGamma, coef0 = coef0, degree = degree, probability = T, scale = F)
    predData <- predict(svmRs, testDataNoClass, probability = F)
    prob <- predict(svmRs, testDataNoClass, probability = T)

    probDf <- prob %>%
      attr(., "probabilities") %>%
      as.data.frame() %>%
      rownames_to_column("SampleID")
    predDf1 <- probDf %>%
      rowwise() %>%
      do({
        result <- as.data.frame(.)
        values <- result[1,] %>%
          select(-c("SampleID")) %>%
          unlist()
        result$Value <- values[1]
        result
      }) %>%
      select(c("SampleID", "Value")) %>%
      add_column(Prediction = predData)
    predictFinalDf1 <- sampleInfo %>%
      filter(SampleID %in% rownames(testData)) %>%
      left_join(predDf1, by = c("SampleID")) %>%
      mutate(Fold = k)

    predDf <- probDf %>%
      rowwise() %>%
      do({
        result <- as.data.frame(.)
        values <- result[1,] %>%
          select(-c("SampleID")) %>%
          unlist()
        result$Probability <- max(values)
        result
      }) %>%
      select(c("SampleID", "Probability")) %>%
      add_column(Prediction = predData)
    predictFinalDf <- sampleInfo %>%
      filter(SampleID %in% rownames(testData)) %>%
      left_join(predDf, by = c("SampleID")) %>%
      rename(Sample = SampleID) %>%
      select(-c("Probability"), "Probability") %>%
      mutate(Test_in_CV_fold = k)

    list(predictDf = predictFinalDf, plotData = predictFinalDf1)
  })
predictDf <- predictLists %>%
  map_dfr(function(list) {
    list$predictDf
  })
predictDf
write.csv(predictDf, "SVM_Prediction_CV.csv", row.names = F)

plotData <- predictLists %>%
  map_dfr(function(list) {
    list$plotData
  })
plotData

write_tsv(plotData, "Classification_Result.txt")

predictDf$ClassNote <- predictDf$ClassNote %>%
  as.factor()
predictDf$Prediction <- predictDf$Prediction %>%
  factor(., levels = levels(predictDf$ClassNote))

pre_summary = table(predictDf$ClassNote, predictDf$Prediction)
print(pre_summary)
print(pre_summary %>% as.data.frame())
summaryTb <- pre_summary %>%
  as.data.frame() %>%
  as_tibble() %>%
  rename(Var1 = 1, Var2 = 2) %>%
  spread(Var2, "Freq")
print("=log=")
print(summaryTb)
summaryMatrix <- summaryTb %>%
  select(-"Var1") %>%
  as.matrix()
diagSum <- sum(diag(summaryMatrix))
sum <- sum(summaryMatrix)
predictive <- (diagSum / sum) %>%
  round(3)
finalSummaryTb <- summaryTb %>%
  mutate(`Model predictive accuracy` = c(predictive, "")) %>%
  rename(` ` = Var1)
print(finalSummaryTb)

write_csv(finalSummaryTb, "SVM_Prediction_Summary_CV_Overall.csv")











